var http = require("https");
var iconv = require('iconv-lite');
var cheerio = require("cheerio");
var email = require("emailjs/email");

var domain = 'https://www.dygod.net';
var url = "https://www.dygod.net/html/gndy/dyzz/";

function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
}

function download(url) {
    return new Promise(function (resolve, reject) {
        var htmlData = [];
        var htmlDataLength = 0;
        http.get(url, function (res) {
            res.on('data', function (chunk) {
                htmlData.push(chunk);
                htmlDataLength += chunk.length;
            });
            res.on("end", function () {
                var data = iconv.decode(Buffer.concat(htmlData, htmlDataLength), 'gbk');
                resolve(data);
            });
        }).on("error", function () {
            resolve('');
        });
    });
}

function send_email(lists) {
    var body = '';
    for (let i = 0; i < lists.length; i++) {
        body += `${lists[i][0]}\n`;
    }
    var server = email.server.connect({
        user: "发件人的qq邮箱账号",
        password: "发件人的qq邮箱密码",
        host: "smtp.qq.com",
        ssl: true
    });
    return new Promise((resolve, reject) => {
        server.send({
            text: body,
            from: "你的qq邮箱账号",
            to: "收件人邮箱",
            subject: "电影天堂最新电影：" + getNowFormatDate(),
        }, function (err, message) {
            if (err) {
                console.log('发生了错误', err);
                reject(false);
            } else {
                //console.log('发送成功');
                resolve(true);
            }
        });
    });
}

async function start() {
    console.log('start fetching...');

    var html = await download(url);
    if (!html) return;

    var $ = cheerio.load(html, { decodeEntities: false });
    var total = $(".co_content8 a.ulink").length;
    var all_address = [];
    $(".co_content8 a.ulink").each(function (i, e) {
        var address = domain + $(e).attr('href');
        all_address.push(address);
    });

    var promises = all_address.map((add) => {
        return download(add);
    });
    var results = await Promise.all(promises);

    var lists = [];
    for (var i = 0; i < results.length; i++) {
        var data = results[i];
        if (!data) continue;
        var $$ = cheerio.load(data, { decodeEntities: false });
        var download_title = $$('div.title_all h1').text();
        var download_url = $$('a[href^="magnet:"]').eq(0).attr('href');

        if (download_title && download_url) {
            lists.push([download_title, download_url]);
        }
    }

    console.log("done [" + total + "]");
    var r = await send_email(lists);
    console.log('邮件发送结果', r ? '[成功]' : '[失败]');

}

start();